package d0904;
import java.io.UnsupportedEncodingException;

public class 字符串 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = new String("hello");

        char[] chars =  {'你','好'};
        s = new String (chars);
        System.out.println(s);

        byte[] bytes = {90,89,88};
        s = new String(bytes);
        System.out.println(s);

        s.toCharArray();// 转字符串数组
        s.getBytes("UTF-8");// 转字节数组字符集名

        System.out.println(s.length());

        s = "静夜思 李白: 床前明月光，疑是地上霜。举头望明月，低头思故乡。";

        int index = s.indexOf("床");
        String title = s.substring(0, index);  // 截取标题
        String content = s.substring(index);

        System.out.println(title);

        String[] lines = content.split("[，。]");
        for (int i = 0; i < lines.length; i++) {
            System.out.println(lines[i]);
        }

        // s.charAt(index)  输出指定下标处的字符


        // 字符串的不变性
        String a = "hello";
        String b = " world";
        System.out.println(a.hashCode());
        a = a + b;  // a 重新被赋值,  和之前的 a 不是同一个对象
        System.out.println(a);
        System.out.println(a.hashCode());
        String c = a.replace("l", "K");  // a 值不变
        System.out.println(a);
        System.out.println(c);

        // 可变字符串
        StringBuilder sb = new StringBuilder(a);
        long time = System.currentTimeMillis(); // 时间戳
        for (int i = 0; i < 100000; i++) {
            // a += "a";
            sb.append("a");
        }
        time  = System.currentTimeMillis() - time;
        System.out.println("消耗时间:" + time);

        StringBuffer sb1 = new StringBuffer(a);

        /**
         * StringBuilder  线程不安全, 效率高 ==> 单线程编程
         * StringBuffer   线程安全,   效率低 ==> 多线程编程
         */

    }
}
